package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.format.DateTimeFormatter;
import java.util.List;

@Controller
public class UserListController {

    @Autowired
    private UserService userService;

    // 暂时移除@PreAuthorize注解进行测试
    @GetMapping(value = "/user-list", produces = MediaType.TEXT_HTML_VALUE + ";charset=UTF-8")
    @ResponseBody
    public byte[] getUserList() {
        // 获取所有用户列表
        List<User> users = userService.findAll();
        
        // 创建HTML响应
        StringBuilder html = new StringBuilder();
        html.append("<!DOCTYPE html>");
        html.append("<html>");
        html.append("<head>");
        html.append("    <meta charset='UTF-8'>");
        html.append("    <title>用户列表</title>");
        html.append("</head>");
        html.append("<body>");
        html.append("    <h1>用户列表</h1>");
        
        if (users.isEmpty()) {
            html.append("    <p>暂无用户数据</p>");
        } else {
            html.append("    <table border='1'>");
            html.append("        <tr>");
            html.append("            <th>用户名</th>");
            html.append("            <th>邮箱</th>");
            html.append("        </tr>");
            
            for (User user : users) {
                html.append("        <tr>");
                html.append("            <td>").append(user.getUsername()).append("</td>");
                html.append("            <td>").append(user.getEmail()).append("</td>");
                html.append("        </tr>");
            }
            
            html.append("    </table>");
        }
        
        html.append("</body>");
        html.append("</html>");
        
        return html.toString().getBytes();
    }
}